package com.qiang.util;

import com.github.benmanes.caffeine.cache.*;
import org.springframework.context.annotation.Bean;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @package: com.qiang.util
 * @title: CacheUtil
 * @projectName: burning
 * @description: //TODO
 * @author zhuhongqiang3
 * @date:  2020-06-28 15:23
 * @version: V1.0
 * @retrun com.qiang.util.burning
 */
@Component
public class CacheUtil {

    @Bean
    public Cache<String, String> cacheBuilder(){
        Cache<String, String> cache = Caffeine.newBuilder()
                // 数量上限
                .maximumSize(1024)
                // 过期机制
                .expireAfterWrite(5, TimeUnit.MINUTES)
                // 弱引用key
                .weakKeys()
                // 弱引用value
                .weakValues()
                // 剔除监听
                .removalListener((RemovalListener<String, String>) (key, value, cause) ->
                        System.out.println("key:" + key + ", value:" + value + ", 删除原因:" + cause.toString()))
                .build();
        return cache;
    }

    @Bean
    public AsyncLoadingCache<String, String> cacheAsyBuilder() throws InterruptedException, ExecutionException, TimeoutException {
        AsyncLoadingCache<String, String> cache = Caffeine.newBuilder()
                // 数量上限
                .maximumSize(2)
                // 失效时间
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .refreshAfterWrite(1, TimeUnit.MINUTES)
                // 异步加载机制
                .buildAsync(new CacheLoader<String, String>() {
                    @Nullable
                    @Override
                    public String load(@NonNull String key) throws Exception {
                        return "from redis";
                    }
                });
        System.out.println(cache.get("username").get());
        System.out.println(cache.get("password").get(10, TimeUnit.MINUTES));
        System.out.println(cache.get("username").get(10, TimeUnit.MINUTES));
        System.out.println(cache.get("blog").get());
        return cache;
    }
}
